package com.xly.webclick.adapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.xly.webclick.base.BaseItemViewModel;
import com.xly.webclick.base.BaseViewModel;

import java.util.List;


/**
 * Created by amos on 2018/5/15.
 */
public class CommonBindingRecyclerAdpter<T extends BaseViewModel> extends RecyclerView.Adapter<CommonBindingViewHolder> {

    private final List<T> mDatas;

    private final int layoutId;

    private final int brId;

    public CommonBindingRecyclerAdpter(List<T> mDatas, int layoutId, int brId) {
        this.mDatas = mDatas;
        this.layoutId = layoutId;
        this.brId = brId;
    }

    @NonNull
    @Override
    public CommonBindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
        CommonBindingViewHolder viewHolder = new CommonBindingViewHolder(binding.getRoot());
        viewHolder.setBinding(binding);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CommonBindingViewHolder holder, int position) {
        holder.getBinding().setVariable(brId, mDatas.get(position));
        holder.getBinding().executePendingBindings();
        if (mDatas.get(position) instanceof BaseItemViewModel) {
            holder.setViewModel((BaseItemViewModel) mDatas.get(position));
            ((BaseItemViewModel) mDatas.get(position)).setCommonBindingViewHolder(holder);
        }
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull CommonBindingViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        if (holder.getViewModel() != null) {
            holder.getViewModel().onDestroy();
        }
    }

    @Override
    public void onViewAttachedToWindow(@NonNull CommonBindingViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        if (holder.getViewModel() != null) {
            holder.getViewModel().onCreate(null);
        }

    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }


    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }
}
